package cn.innosmart.aq.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.NumberPicker;
import android.widget.RadioButton;
import android.widget.TextView;

import com.tutk.p2p.ConnectionEntity;
import com.tutk.p2p.ConnectionManager;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.Calendar;

import cn.innosmart.aq.R;
import cn.innosmart.aq.bean.ActionBean;
import cn.innosmart.aq.bean.AquariumBean;
import cn.innosmart.aq.bean.CommandBean;
import cn.innosmart.aq.bean.DeviceBean;
import cn.innosmart.aq.bean.SceneBean;
import cn.innosmart.aq.bean.ScheduleBean;
import cn.innosmart.aq.customize.CustomCheckBox;
import cn.innosmart.aq.customize.PrioritySetDialog;
import cn.innosmart.aq.manager.ScheduleManager;
import cn.innosmart.aq.util.DeviceConstant;
import cn.innosmart.aq.util.SharedUtil;
import cn.innosmart.aq.util.SystemConstant;
import cn.innosmart.aq.view.activity.base.BaseActivity;

/**
 * Created by David on 2015/8/12.
 */
public class ScheduleActivity extends BaseActivity implements NumberPicker.Formatter, NumberPicker.OnValueChangeListener, NumberPicker.OnScrollListener {
    private final int EXIT = 0;
    public AquariumBean aquariumBean;
    int[] priorityStrIds = new int[]{R.string.priority_ignore_simple, R.string.priority_normal_simple, R.string.priority_important_simple, R.string.priority_high_important_simple};
    private String flag;
    private String scheduleId;
    private ConnectionEntity connectionEntity;
    private ImageView ivNameIcon;
    private int type;
    private String sceneId;
    private String deviceAddress;
    private DeviceBean deviceBean;
    private SceneBean sceneBean;
    private NumberPicker hourPicker;
    private NumberPicker minutePicker;
    private EditText etScheduleName;
    private CheckBox cbEnable;
    private ScheduleBean scheduleBean;
    private TextView tvDevicename;
    private RadioButton rbOpen;
    private RadioButton rbClose;
    private CustomCheckBox week0;
    private CustomCheckBox week1;
    private CustomCheckBox week2;
    private CustomCheckBox week3;
    private CustomCheckBox week4;
    private CustomCheckBox week5;
    private CustomCheckBox week6;
    /**
     * 设置界面Toolbar
     */
    private Toolbar toolbar;
    private Menu menus;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case EXIT:
                    exit();
                    break;
            }
        }
    };
    private int position = -1;
    private Toolbar.OnMenuItemClickListener onMenuItemClick = new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            switch (menuItem.getItemId()) {
                case R.id.schedule_add_action:
                    //添加ACtion
                    String scheduleName = etScheduleName.getText().toString().trim();
                    if (TextUtils.isEmpty(scheduleName)) {
                        showToast(getString(R.string.name_can_not_empty));
                        break;
                    }
                    scheduleBean.setIcon_data("icon_data");
                    scheduleBean.setIcon_type("icon_type");
                    scheduleBean.setTitle(scheduleName);
                    if (TextUtils.isEmpty(scheduleName)) {
                        showToast(getString(R.string.name_can_not_empty));
                        break;
                    }
                    if (checkRepeatTitle(scheduleName)) {
                        showToast(getString(R.string.name_had_used));
                        break;
                    }
                    caclulateTimeLine();
                    if (scheduleBean.getTimeline().length() == 0) {
                        showToast(getString(R.string.week_can_not_empty));
                        break;
                    }
                    if (scheduleId == null) {
                        addSchedule();
                    } else {
                        modifySchedule();
                    }
                    break;
            }
            return true;
        }
    };
    private CheckBox cbPushMessage;
    private TextView tvPriority;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_schedule);
        String aquariumId = getIntent().getStringExtra("aquarium");
        type = getIntent().getIntExtra("type", 0);
        aquariumBean = AquariumBean.findAquariumById(aquariumId);

        assignViews();
        scheduleId = getIntent().getStringExtra("schedule");
        initPosition();
        connectionEntity = ConnectionManager.getInstance().getCurrentConnectionEntity();
        deviceAddress = getIntent().getStringExtra("device");
        sceneId = getIntent().getStringExtra("scene");
        //初始化数据  添加 或者修改
        if (scheduleId == null) {
            scheduleBean = new ScheduleBean();
            scheduleBean.setPlace(aquariumBean.getId());
            scheduleBean.setScheduleCommands(new ArrayList<CommandBean>());
            CommandBean commandBean = new CommandBean();
            commandBean.setOrder(1);
            if (deviceAddress != null) {
                deviceBean = SystemConstant.deviceBeanHashMap.get(deviceAddress);
                commandBean.setType("commands");
                ArrayList<ActionBean> actionBeans = new ArrayList<>();
                ActionBean actionBean = new ActionBean();
                actionBean.setOrder(1);
                actionBean.setAddress(deviceBean.getAddress());
                actionBean.setField("basicvalue");
                actionBeans.add(actionBean);
                commandBean.setCommand(actionBeans);
            } else if (sceneId != null) {
                sceneBean = SceneBean.queryScene(sceneId);
                commandBean.setType("scene");
                commandBean.setScene_id(sceneBean.getId());
            }
            //默认pns_priority为1
            scheduleBean.pns_priority = 1;
            scheduleBean.setPns("pns");
            scheduleBean.getScheduleCommands().add(commandBean);
        } else {
            scheduleBean = new ScheduleBean();
            for (int i = 0; i < aquariumBean.getScheduleList().size(); i++) {
                ScheduleBean scheduleBeans = (ScheduleBean) aquariumBean.getScheduleList().get(i);
                if (scheduleId.equals(scheduleBeans.getId())) {
                    scheduleBean.setId(new String(scheduleBeans.getId()));
                    scheduleBean.setTitle(new String(scheduleBeans.getTitle()));
                    scheduleBean.setIcon_data(new String(scheduleBeans.getIcon_data()));
                    scheduleBean.setIcon_type(new String(scheduleBeans.getIcon_type()));
                    scheduleBean.setEnabled(scheduleBeans.getEnabled());
                    scheduleBean.pns_priority = scheduleBeans.pns_priority;
                    scheduleBean.setTimeline(scheduleBeans.getTimeline());
                    scheduleBean.setTime(scheduleBeans.getTime());
                    scheduleBean.setPns(scheduleBeans.getPns() == null ? null : new String(scheduleBeans.getPns()));
                    scheduleBean.setPlace(new String(scheduleBeans.getPlace()));
                    ArrayList<CommandBean> commandBeans = new ArrayList<CommandBean>();
                    commandBeans.addAll(scheduleBeans.getScheduleCommands());
                    scheduleBean.setScheduleCommands(commandBeans);
                    break;
                }
            }
            CommandBean commandBean = scheduleBean.getScheduleCommands().get(0);
            if (commandBean.getType().equals("scene")) {
                sceneBean = SceneBean.queryScene(commandBean.getScene_id());
            } else if (commandBean.getType().equals("commands")) {
                deviceBean = SystemConstant.deviceBeanHashMap.get(commandBean.getCommand().get(0).getAddress());
            }
        }
        setBar();
        init();
        initListener();
    }

    /**
     * 初始化监听器
     */
    private void initListener() {
        rbOpen.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b)
                    scheduleBean.getScheduleCommands().get(0).getCommand().get(0).setValue(255);
            }
        });
        rbClose.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b)
                    scheduleBean.getScheduleCommands().get(0).getCommand().get(0).setValue(0);
            }
        });
        cbPushMessage.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    scheduleBean.setPns("pns");
                } else {
                    scheduleBean.setPns(null);
                }
            }
        });
    }

    //初始化数据内容
    private void init() {
        String time = scheduleBean.getTime();
        int hour;
        int minute;
        if (time == null) {
            Calendar c = Calendar.getInstance();
            c.setTimeInMillis(System.currentTimeMillis());
            hour = c.get(Calendar.HOUR_OF_DAY);
            minute = c.get(Calendar.MINUTE);
        } else {
            String[] times = time.split(":");
            hour = Integer.valueOf(times[0]);
            minute = Integer.valueOf(times[1]);
        }
        tvPriority.setText(priorityStrIds[scheduleBean.pns_priority]);
        tvPriority.setTag(scheduleBean.pns_priority);
        hourPicker.setFormatter(this);
        hourPicker.setOnValueChangedListener(this);
        hourPicker.setOnScrollListener(this);
        hourPicker.setMaxValue(23);
        hourPicker.setMinValue(0);
        hourPicker.setValue(hour);
        minutePicker.setFormatter(this);
        minutePicker.setOnValueChangedListener(this);
        minutePicker.setOnScrollListener(this);
        minutePicker.setMaxValue(59);
        minutePicker.setMinValue(0);
        minutePicker.setValue(minute);

        if (scheduleBean.getEnabled() == 1) {
            cbEnable.setChecked(true);
        } else {
            cbEnable.setChecked(false);
        }
        String pns = scheduleBean.getPns();
        if (pns == null) {
            cbPushMessage.setChecked(false);
        } else if (pns.equals("pns")) {
            cbPushMessage.setChecked(true);
        }
        if (scheduleId == null) {
            cbPushMessage.setChecked(true);
        }
        if (scheduleId != null) {
            etScheduleName.setText(scheduleBean.getTitle());
        }
        if (deviceBean != null) {
            if (deviceBean.getUserTag() != null)
                tvDevicename.setText(DeviceConstant.nameMap.get(deviceBean.getUserTag()));
            else
                tvDevicename.setText(deviceBean.getName());
            if (scheduleBean.getScheduleCommands().get(0).getCommand().get(0).getValue() == 255)
                rbOpen.setChecked(true);
            else
                rbClose.setChecked(true);

            if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_FEEDER) {
                rbClose.setVisibility(View.GONE);
            } else {
                rbClose.setVisibility(View.VISIBLE);
            }
        }
        if (sceneBean != null) {
            tvDevicename.setText(String.format(getString(R.string.format_scene), sceneBean.getTitle()));
            rbClose.setVisibility(View.GONE);
        }

        if (scheduleId != null) {
            JSONArray jsonArray = scheduleBean.getTimeline();
            for (int i = 0; i < jsonArray.length(); i++) {
                try {
                    JSONArray jsonTime = jsonArray.getJSONArray(i);
                    int startIndex = (int) jsonTime.get(0);
                    switch (startIndex) {
                        case 0:
                            week0.setChecked(true);
                            break;
                        case 1440:
                            week1.setChecked(true);
                            break;
                        case 2880:
                            week2.setChecked(true);
                            break;
                        case 4320:
                            week3.setChecked(true);
                            break;
                        case 5760:
                            week4.setChecked(true);
                            break;
                        case 7200:
                            week5.setChecked(true);
                            break;
                        case 8640:
                            week6.setChecked(true);
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //初始化控件
    private void assignViews() {
        tvPriority = (TextView) findViewById(R.id.tv_priority);
        tvPriority.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPriorityWindow(tvPriority);
            }
        });
        cbPushMessage = (CheckBox) findViewById(R.id.cb_push_message);
        hourPicker = (NumberPicker) findViewById(R.id.hour_picker);
        minutePicker = (NumberPicker) findViewById(R.id.minute_picker);
        etScheduleName = (EditText) findViewById(R.id.et_schedule_name);
        cbEnable = (CheckBox) findViewById(R.id.cb_enable);
        tvDevicename = (TextView) findViewById(R.id.tv_device);
        rbOpen = (RadioButton) findViewById(R.id.rb_open);
        rbClose = (RadioButton) findViewById(R.id.rb_close);
        ivNameIcon = (ImageView) findViewById(R.id.iv_name_icon);
        cbEnable.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    scheduleBean.setEnabled(1);
                    ivNameIcon.setImageResource(R.drawable.rule_on);
                } else {
                    scheduleBean.setEnabled(0);
                    ivNameIcon.setImageResource(R.drawable.rule_off);
                }
            }
        });
        week0 = (CustomCheckBox) findViewById(R.id.week0);
        week1 = (CustomCheckBox) findViewById(R.id.week1);
        week2 = (CustomCheckBox) findViewById(R.id.week2);
        week3 = (CustomCheckBox) findViewById(R.id.week3);
        week4 = (CustomCheckBox) findViewById(R.id.week4);
        week5 = (CustomCheckBox) findViewById(R.id.week5);
        week6 = (CustomCheckBox) findViewById(R.id.week6);
    }

    /**
     * 格式化字符串
     *
     * @param selectedNum
     * @return
     */
    @NonNull
    private String formateString(ArrayList<String> selectedNum) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < selectedNum.size(); i++) {
            stringBuilder.append(selectedNum.get(i));
            if (i != (selectedNum.size() - 1)) {
                stringBuilder.append(",");
            } else {
                stringBuilder.append("日");
            }
        }
        return stringBuilder.toString();
    }

    /**
     * 设置Toolbar
     */
    private void setBar() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        ((ImageView) findViewById(R.id.iv_headicon)).setImageResource(R.drawable.toolbar_back);
        toolbar.setTitle("");
        if (scheduleId == null) {
            ((TextView) findViewById(R.id.tv_toolbar)).setText(getString(R.string.activity_add_schedule));
        } else {
            ((TextView) findViewById(R.id.tv_toolbar)).setText(getString(R.string.activity_modify_schedule));
        }

        setSupportActionBar(toolbar);
        toolbar.setOnMenuItemClickListener(onMenuItemClick);
        findViewById(R.id.iv_headicon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mHandler.sendEmptyMessage(EXIT);
            }
        });
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }


    /**
     * 计算时间轴
     */
    private void caclulateTimeLine() {
        JSONArray timeline = new JSONArray();
        if (week0.isChecked()) {
            JSONArray jsontime = new JSONArray();
            jsontime.put(0);
            jsontime.put(1440);
            timeline.put(jsontime);
        }
        if (week1.isChecked()) {
            JSONArray jsontime = new JSONArray();
            jsontime.put(1440);
            jsontime.put(2880);
            timeline.put(jsontime);
        }
        if (week2.isChecked()) {
            JSONArray jsontime = new JSONArray();
            jsontime.put(2880);
            jsontime.put(4320);
            timeline.put(jsontime);
        }
        if (week3.isChecked()) {
            JSONArray jsontime = new JSONArray();
            jsontime.put(4320);
            jsontime.put(5760);
            timeline.put(jsontime);
        }
        if (week4.isChecked()) {
            JSONArray jsontime = new JSONArray();
            jsontime.put(5760);
            jsontime.put(7200);
            timeline.put(jsontime);
        }
        if (week5.isChecked()) {
            JSONArray jsontime = new JSONArray();
            jsontime.put(7200);
            jsontime.put(8640);
            timeline.put(jsontime);
        }
        if (week6.isChecked()) {
            JSONArray jsontime = new JSONArray();
            jsontime.put(8640);
            jsontime.put(10080);
            timeline.put(jsontime);
        }
        scheduleBean.setTimeline(timeline);
        String strTime = format(hourPicker.getValue()) + ":" + format(minutePicker.getValue());
        scheduleBean.setTime(strTime);
    }

    /**
     * 修改排程
     */
    private void modifySchedule() {
        loadingDialog();
        //发送修改排程指令
        ScheduleManager.getInstance().Update(connectionEntity, scheduleBean.toParams(), new ScheduleManager.UpdateCallBack() {
            @Override
            public void onUpdateResponseCallBack(int ret, String id) {
                if (ret == 0) {
                    for (int i = 0; i < aquariumBean.getScheduleList().size(); i++) {
                        ScheduleBean oldscheduleBean = (ScheduleBean) aquariumBean.getScheduleList().get(i);
                        if (id.equals(oldscheduleBean.getId())) {
                            aquariumBean.getScheduleList().remove(i);
                            aquariumBean.getScheduleList().add(scheduleBean);
                            hideloadingDialog();
                            exit();
                        }
                    }
                }
            }
        });
    }

    //添加排程
    private void addSchedule() {
        loadingDialog();
        //发送添加排程的指令
        ScheduleManager.getInstance().Add(connectionEntity, scheduleBean.toParams(), new ScheduleManager.AddCallBack() {
            @Override
            public void onAddResponseCallBack(int ret, String id) {
                scheduleBean.setId(id);
                aquariumBean.getScheduleList().add(scheduleBean);
                hideloadingDialog();
                exit();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_schedule, menu);
        menus = menu;
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    protected void onResume() {
        setBaseDialogContext(this);
        super.onResume();
        toolbar.setNavigationIcon(null);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public String format(int value) {
        String tmpStr = String.valueOf(value);
        if (value < 10) {
            tmpStr = "0" + tmpStr;
        }
        return tmpStr;
    }

    @Override
    public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
    }

    @Override
    public void onScrollStateChange(NumberPicker view, int scrollState) {
    }

    /**
     * 初始化Position 找到 需要修改的排程
     */
    private void initPosition() {
        if (scheduleId != null && aquariumBean.getScheduleList() != null) {
            for (int i = 0; i < aquariumBean.getScheduleList().size(); i++) {
                ScheduleBean scheduleBean = (ScheduleBean) aquariumBean.getScheduleList().get(i);
                if (scheduleBean.getId().equals(scheduleId)) {
                    position = i;
                }
            }
        }
    }

    /**
     * 检查Title是否重复
     * @param title
     * @return
     */
    private boolean checkRepeatTitle(String title) {
        if (scheduleId == null && aquariumBean.getScheduleList() != null) {
            for (Object object : aquariumBean.getScheduleList()) {
                if (title.equals(((ScheduleBean) object).getTitle())) {
                    return true;
                }
            }
        } else if (scheduleId != null && aquariumBean.getScheduleList() != null) {
            for (int i = 0; i < aquariumBean.getScheduleList().size(); i++) {
                if (title.equals(((ScheduleBean) aquariumBean.getScheduleList().get(i)).getTitle())) {
                    if (i == position) {
                        continue;
                    } else {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    //----
    //----
    //
    //----
    //----

    /**
     * 显示优先级对话框
     * @param tvPriority
     */
    private void showPriorityWindow(final TextView tvPriority) {
        final PrioritySetDialog priorityDialog = new PrioritySetDialog(this, (Integer) tvPriority.getTag());
        priorityDialog.setTitle(getString(R.string.alarm_priority_title));
        priorityDialog.setNegativeButton(R.string.cancel, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                priorityDialog.dismiss();
            }
        });
        priorityDialog.setPositiveButton(R.string.sure, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                priorityDialog.checkChange();
            }
        });
        priorityDialog.setOnChangeListener(new PrioritySetDialog.OnChangeListener() {
            @Override
            public void onChange(int type) {
                switch (type) {
                    case 1:
                        if (checkPushStatus()) {
                            priorityDialog.dismiss();
                            tvPriority.setText(getString(priorityStrIds[type]));
                            tvPriority.setTag(type);
                            scheduleBean.pns_priority = type;
                        } else {
                            //跳转到Push界面
                            switchToPushActivity();
                        }
                        break;
                    case 2:
//                        checkPushAndSmsStatus();
                        if (checkPushStatus()) {
                            if (checkSmsStatus()) {
                                priorityDialog.dismiss();
                                tvPriority.setText(getString(priorityStrIds[type]));
                                tvPriority.setTag(type);
                                scheduleBean.pns_priority = type;
                            } else {
                                //跳转到SMS界面
                                switchToSmsActivity();
                            }
                        } else {
                            //跳转到Push界面
                            switchToPushActivity();
                        }
                        break;
                    case 3:
                        if (checkPushStatus()) {
                            if (checkTelStatus()) {
                                priorityDialog.dismiss();
                                tvPriority.setText(getString(priorityStrIds[type]));
                                tvPriority.setTag(type);
                                scheduleBean.pns_priority = type;
                            } else {
                                //跳转到Tel界面
                                switchToTelActivity();
                            }
                        } else {
                            //跳转到Push界面
                            switchToPushActivity();
                        }
                        break;
                }
            }
        });
        priorityDialog.setCanceledOnTouchOutside(true);
        priorityDialog.show();
    }

    private void switchToTelActivity() {
        Intent intent = new Intent(this, TelPushMessageActivity.class);
        startActivityForResult(intent, 1);
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }

    private void switchToSmsActivity() {
        Intent intent = new Intent(this, SmsPushMessageActivity.class);
        startActivityForResult(intent, 1);
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }

    private void switchToPushActivity() {
        Intent intent = new Intent(this, PushMessageSettingAcitivity.class);
        startActivityForResult(intent, 1);
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }

    private boolean checkTelStatus() {
        if (SharedUtil.getInstance().readTelStatus(connectionEntity.getUid())) {
            //关闭对话框
            return true;
        } else {
            //跳转到Push界面
            return false;
        }
    }

    private boolean checkSmsStatus() {
        if (SharedUtil.getInstance().readSmsStatus(connectionEntity.getUid())) {
            //关闭对话框
            return true;
        } else {
            //跳转到Push界面
            return false;
        }
    }

    private boolean checkPushStatus() {
        if (SharedUtil.getInstance().readXinStatus(connectionEntity.getUid())) {
            //关闭对话框
            return true;
        } else {
            //跳转到Push界面
            return false;
        }
    }
}
